package com.dmlll.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dmlll.common.ResultObj;
import com.dmlll.domain.User;
import com.dmlll.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@RestController
@RequestMapping("login")
public class LoginController {
    @Autowired
    private UserService userService;
    @RequestMapping("login")
    public ResultObj login(User user,HttpSession session,String code){
        //用户认证
        Subject subject = SecurityUtils.getSubject();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("acount",user.getAcount());
        User theUser = userService.getOne(queryWrapper);
        String c = (String) session.getAttribute("code");
        if(c.equals(code)) {
            //该用户存在
            if (theUser != null) {
                //密码正确
                if (theUser.getPassword().equals(user.getPassword())) {
                    session.setAttribute("user",theUser);
                    return ResultObj.LOGIN_SUCCESS;
                }
                return ResultObj.LOGIN_PWD_ERROR;
            }
            return ResultObj.LOGIN_ACC_ERROR;
        }
        return ResultObj.LOGIN_CODE_ERROR;
    }
    @RequestMapping("/getCode")
    public void getCode(HttpServletResponse response, HttpSession session){
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(116,34,4,20);
        session.setAttribute("code",lineCaptcha.getCode());
        try{
            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(lineCaptcha.getImage(),"JPEG",outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("logout")
    public void logout(HttpSession session){
        session.invalidate();
    }
}
